package com.hs.srm.admin.modules.sys.controller;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import sunnykid.character.UtilCharacter;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.base.common.utils.Constant;
import com.hs.srm.base.common.utils.DictDataUtil;
import com.hs.srm.base.common.utils.DictDataUtil.DictType;
import com.hs.srm.base.modules.sys.entity.SysDictEntity;
import com.hs.srm.base.modules.sys.service.SysDictService;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.R;

/**
 * 数据字典
 **/
@Controller
@RequestMapping("/sys/dict")
public class SysDictController extends AbstractController {

	private static final long serialVersionUID = 6586657882337832897L;
	@Autowired
	private SysDictService sysDictService;

	// @RequiresPermissions("sys:dict:list")
	@RequestMapping("/list")
	@ResponseBody
	public List<SysDictEntity> list(@RequestParam Map<String, Object> params) {
		return this.sysDictService.query(params);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST, produces = {"application/json"}, consumes = {"application/x-www-form-urlencoded"})
	@ResponseBody
	public R add(SysDictEntity data) {
		if(data.getTypeId() == null) {
			data.setTypeId(Long.valueOf(SysDictEntity.PARENT_ID_FOR_TYPE));
		}
		List<SysDictEntity> dicts = DictDataUtil.getAllDict();
		for(SysDictEntity dict : dicts) {
			if(data.getTypeId().equals(dict.getTypeId())
					&& (dict.getTxt().equals(data.getTxt()) || dict.getVal().equals(data.getVal()))) {
				String errorMsg = dict.getTypeOrItem().intValue() == SysDictEntity.IS_TYPE ? "已经有重复类别" : "相同类别下已有重复元素";
				return R.error(errorMsg);
			}
		}
		data.setCreateBy(this.getUserId());
		data.setCreateTime(DateUtils.currentTimestamp());
		this.sysDictService.insert(data);
		DictDataUtil.dictMapAll.put(data.getId(), data);
		return R.ok();
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST, produces = {"application/json"}, consumes = {"application/x-www-form-urlencoded"})
	@ResponseBody
	public R edit(SysDictEntity data) {
		if(data.getTypeId() == null) {
			data.setTypeId(Long.valueOf(SysDictEntity.PARENT_ID_FOR_TYPE));
		}
		List<SysDictEntity> dicts = DictDataUtil.getAllDict();
		for(SysDictEntity dict : dicts) {
			if(data.getTypeId().equals(dict.getTypeId())
					&& (dict.getTxt().equals(data.getTxt()) || dict.getVal().equals(data.getVal()))
					&& !dict.getId().equals(data.getId())) {
				String errorMsg = dict.getTypeOrItem().intValue() == SysDictEntity.IS_TYPE ? "已经有重复类别" : "相同类别下已有重复元素";
				return R.error(errorMsg);
			}
		}
		SysDictEntity orginDict = DictDataUtil.getById(data.getId());
		orginDict.setRemark(data.getRemark());
		orginDict.setVal(data.getVal());
		orginDict.setTxt(data.getTxt());
		orginDict.setTypeId(data.getTypeId());
		orginDict.setUpdateBy(this.getUserId());
		orginDict.setUpdateTime(DateUtils.currentTimestamp());
		this.sysDictService.updateById(orginDict);
		DictDataUtil.dictMapAll.put(data.getId(), orginDict);
		return R.ok();
	}

	@RequestMapping("/delete/{id}")
	@ResponseBody
	public R delete(@PathVariable("id") Long id) {
		SysDictEntity data = this.sysDictService.selectById(id);
		if(data.getTypeOrItem().longValue() == SysDictEntity.IS_ITEM) {// 删除条目
			this.sysDictService.deleteById(id);
			DictDataUtil.dictMapAll.remove(id);
		} else {// 删除类别
			this.sysDictService.deleteById(id);
			this.sysDictService.delete(new EntityWrapper<SysDictEntity>().eq("type_id", id));
			DictDataUtil.flush();
		}
		return R.ok();
	}

	@RequestMapping("/info/{id}")
	@ResponseBody
	public R info(@PathVariable("id") Long id) {
		return R.ok(DictDataUtil.getById(id));
	}

	@RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
	@ResponseBody
	public R changeStatus(Long id, Integer status) {
		SysDictEntity data = DictDataUtil.getById(id);
		data.setStatus(status);
		data.setUpdateBy(this.getUserId());
		data.setUpdateTime(DateUtils.currentTimestamp());
		this.sysDictService.updateById(data);
		DictDataUtil.dictMapAll.put(data.getId(), data);
		return R.ok().put("data", data);
	}

	/**
	 * 获取所有类别
	 * @return
	 */
	@RequestMapping("/allType")
	@ResponseBody
	public R getAllType() {
		return R.ok(DictDataUtil.getAllType());
	}

	/**
	 * 跳转至字典项编辑页面
	 * @param id
	 * @return
	 */
	@RequestMapping("/toEdit/{id}")
	public ModelAndView toEdit(@PathVariable("id") Long id) {
		SysDictEntity dict = DictDataUtil.getById(id);
		ModelAndView modelAndView = new ModelAndView("modules/sys/dict/dict_edit");
		modelAndView.addObject("dict", dict);
		return modelAndView;
	}

	/**
	 * 跳转至字典项新增页面
	 * @param typeId
	 * @return
	 */
	@RequestMapping("/toAdd/{typeId}")
	public ModelAndView toAdd(@PathVariable("typeId") Long typeId) {
		ModelAndView modelAndView = new ModelAndView("modules/sys/dict/dict_add");
		modelAndView.addObject("typeId", typeId);
		return modelAndView;
	}

	/**
	 * 获取指定类别下所有启用的字典
	 * @return
	 */
	@RequestMapping("/getDictData")
	@ResponseBody
	public R getDictData(String dictTypeName) {
		// LinkedHashMap 存进去的顺序和取出来的是一样的
		Map<String, String> dataMap = new LinkedHashMap<String, String>();
		// 得到枚举编码
		DictType dictType = DictDataUtil.DictType.getType(dictTypeName);
		if(dictType != null) {
			// 得到字典元素(是否包含父类)
			List<SysDictEntity> dicts = DictDataUtil.getByType(dictType, false);
			for(SysDictEntity dict : dicts) {
				if(dict.getStatus() != null && dict.getStatus().intValue() == Constant.DataStatus.NORMAL.getValue()) {
					dataMap.put(dict.getVal(), dict.getTxt());
				}
			}
		}
		return R.ok(dataMap);
	}

	/**
	 * 根据字典值获取字典文本
	 * @return
	 */
	@RequestMapping("/getDictTextByVal")
	@ResponseBody
	public R getDictTextByVal(String dictTypeName, String dictVal) {
		String txt = DictDataUtil.valToTxt(dictVal, DictDataUtil.DictType.valueOf(dictTypeName));
		return R.ok(txt == null ? UtilCharacter.EMPTY : txt);
	}

	/**
	 * 刷新缓存
	 * @return
	 */
	@RequestMapping("/flushCache")
	@ResponseBody
	public R flushCache() {
		DictDataUtil.flush();
		return R.ok();
	}

}
